package com.JavaNet.chapter7_urlConnection;

import java.io.*;
import java.net.*;


/**
 * 示例 7-2
 * 使用正确的编码下载页面
 */
public class EncodingAwareSourceViewer {


    private static final String BAIDU = "http://www.baidu.com";


    public static void main(String[] args) {

        try {
            // set default encoding
            //String encoding = "ISO-8859-1";
            String encoding = "utf-8";
            URL url = new URL(BAIDU);
            URLConnection urlConnection = url.openConnection();
            String contentType = urlConnection.getContentType();
            System.out.println(urlConnection.getHeaderFields().toString());
            System.out.println("contentType = " + contentType);
            int encodingStart = contentType.indexOf("charset=");
            if (encodingStart != -1) {
                encoding = contentType.substring(encodingStart + 8);
            }
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            Reader r = new InputStreamReader(in, encoding);
            int c;
            while ((c = r.read()) != -1) {
                System.out.print((char) c);
            }
            r.close();
        } catch (MalformedURLException ex) {
            System.err.println(args[0] + " is not a parseAble URL");
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Server sent an encoding Java does not support: " + ex.getMessage());
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }

    }
}
